package com.greensam.pixelengine.service.impl;

import com.greensam.pixelengine.pojo.base.PaginationResponse;
import com.greensam.pixelengine.pojo.entity.PermissionPo;
import com.greensam.pixelengine.pojo.entity.QPermissionPo;
import com.greensam.pixelengine.pojo.query.PermissionPageQuery;
import com.greensam.pixelengine.repository.PermissionRepository;
import com.greensam.pixelengine.service.PermissionDataService;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Ma Chengrui
 * @since 2025/9/29 11:15
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PermissionDataServiceImpl implements PermissionDataService {

    private final JPAQueryFactory jpaQueryFactory;
    private final PermissionRepository permissionRepository;

    @Override
    public PaginationResponse<PermissionPo> pagePermission(PermissionPageQuery pageQuery) {
        return null;
    }

    @Override
    public Optional<PermissionPo> getPermissionById(Long id) {
        return Optional.empty();
    }

    @Override
    public Optional<PermissionPo> getPermissionByCode(String code) {
        if (Objects.isNull(code)) {
            return Optional.empty();
        }
        QPermissionPo p = QPermissionPo.permissionPo;
        return Optional.ofNullable(jpaQueryFactory.selectFrom(p)
                .where(p.code.eq(code)
                        .and(p.delete.eq(Boolean.FALSE)))
                .fetchOne());
    }

    @Override
    public PermissionPo save(PermissionPo permissionPo) {
        if (Objects.isNull(permissionPo)) {
            return null;
        }
        return permissionRepository.save(permissionPo);
    }

    @Override
    public List<PermissionPo> listAllPermission() {
        return List.of();
    }

    @Override
    public List<PermissionPo> listPermissionByIds(Collection<Long> permissionIds) {
        if (permissionIds.isEmpty()) {
            return Collections.emptyList();
        }
        QPermissionPo permissionPo = QPermissionPo.permissionPo;
        return jpaQueryFactory.selectFrom(permissionPo)
                .where(permissionPo.id.in(permissionIds)
                        .and(permissionPo.delete.eq(Boolean.FALSE)))
                .fetch();
    }

    @Override
    public List<PermissionPo> listPermissionByCodes(Collection<String> codes) {
        if (codes.isEmpty()) {
            return Collections.emptyList();
        }
        QPermissionPo permissionPo = QPermissionPo.permissionPo;
        return jpaQueryFactory.selectFrom(permissionPo)
                .where(permissionPo.code.in(codes)
                        .and(permissionPo.delete.eq(Boolean.FALSE)))
                .fetch();
    }
}
